//
//  SmallDecisionsPlateView.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/6/14.
//

#import "SmallDecisionsPlateView.h"
#import <AudioToolbox/AudioToolbox.h>

SmallDecisionsPlateView *plateView;
CGFloat afterTime = 0.01;

@interface SmallDecisionsPlateView () <CAAnimationDelegate>

@property (nonatomic, strong) CAShapeLayer *plateShapeLayer;
@property (nonatomic, strong) CALayer *platePointLayer;
@property (nonatomic, strong) CALayer *imageLayer;
@property (nonatomic, assign) BOOL isplateAnimating;
@property (nonatomic, assign) NSInteger targetIndex;

@end

@implementation SmallDecisionsPlateView
- (instancetype)init {
    self = [super init];
    if (self) {
        plateView = self;
    }
    return self;
}

- (void)startPlateDraw {
    CGRect plateRect = self.bounds;
    CGFloat plateBorderWidth = 40;

    [self.layer removeAllSublayers];
    [self.plateShapeLayer removeAllSublayers];
    [self.plateShapeLayer removeAllAnimations];
    
    [self.layer addSublayer:self.plateShapeLayer];
    [self.layer addSublayer:self.platePointLayer];
    
    self.plateShapeLayer.frame = self.bounds;
    self.plateShapeLayer.borderColor = [UIColor colorWithHexString:@"0xFF5F5F"].CGColor;
    self.plateShapeLayer.borderWidth = plateBorderWidth / 2.0;
    self.plateShapeLayer.cornerRadius = plateRect.size.width / 2.0;
    
    UIBezierPath *plateBezierPath = [UIBezierPath bezierPath];
    [plateBezierPath addArcWithCenter:CGPointMake(plateRect.size.width / 2.0, plateRect.size.height / 2.0) radius:(plateRect.size.height - 40) / 2.0 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    self.plateShapeLayer.path = plateBezierPath.CGPath;
    
    self.platePointLayer.frame = CGRectMake(plateRect.size.width / 2.0 - 35, plateRect.size.height / 2.0 - 35, 70, 70);
    self.imageLayer.frame = CGRectMake(0, 0, 70, 70);
    
    NSInteger count = self.data.count;
    CGFloat offset = (M_PI / count) + M_PI / 2;
    for (int i = 0; i < count; i ++) {
        CGFloat width      = plateRect.size.width / 2.0;
        CGFloat height     = plateRect.size.height / 2.0;
        CGFloat circleRadius = width - plateBorderWidth / 4.0;
        CGFloat plateRadius     = plateRect.size.width / 2.0 - plateBorderWidth / 2.0;
        CGFloat plateStartAngle = i * (M_PI * 2 / count);
        CGFloat plateEndAngle   = (i + 1) * (M_PI * 2 / count);
        
        CAShapeLayer *plateShapeLayer = [CAShapeLayer layer];
        if (i <= 5) {
            plateShapeLayer.fillColor = [UIColor colorWithRed:0.99 green:0.89 blue:(150 + i * 20) / 255.0 alpha:1].CGColor;
        } else if (i <= 10) {
            plateShapeLayer.fillColor = [UIColor colorWithRed:0.99 green:((10 - i) * 20 + 150) / 255.0 blue:0.66 alpha:1].CGColor;
        } else if (i <= 15) {
            plateShapeLayer.fillColor = [UIColor colorWithRed:((15 - i) * 20 + 150) / 255.0 green:0.89 blue:0.66 alpha:1].CGColor;
        } else if (i <= 20)  {
            plateShapeLayer.fillColor = [UIColor colorWithRed:1 green:0.98 blue:(150 + 20 * (20 - i)) / 255.0 alpha:1].CGColor;
        } else if (i <= 25) {
            plateShapeLayer.fillColor = [UIColor colorWithRed:1 green:((25 - i) * 20 + 150) / 255.0 blue:0.85 alpha:1].CGColor;
        } else {
            UIColor *randomColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
            plateShapeLayer.fillColor = randomColor.CGColor;
        }
        UIBezierPath *plateBezierPath = [UIBezierPath bezierPath];
        [plateBezierPath moveToPoint:CGPointMake(plateRect.size.width / 2.0, plateRect.size.height / 2.0)];
        [plateBezierPath addArcWithCenter:CGPointMake(plateRect.size.width / 2.0, plateRect.size.height / 2.0) radius:plateRadius startAngle:plateStartAngle - offset endAngle:plateEndAngle - offset clockwise:YES];
        plateShapeLayer.path = plateBezierPath.CGPath;
        [self.plateShapeLayer addSublayer:plateShapeLayer];

        CATextLayer *plateTextLayer = [CATextLayer layer];
        plateTextLayer.fontSize = 14;
        plateTextLayer.foregroundColor = [UIColor grayColor].CGColor;
        // 水平方向居中对齐
        plateTextLayer.alignmentMode   = @"center";
        // 文本裁剪 - 不裁剪
        plateTextLayer.truncationMode  = kCATruncationNone;
        // 自动换行
        plateTextLayer.wrapped = YES;
        plateTextLayer.contentsScale   = [UIScreen mainScreen].scale;
        plateTextLayer.frame = CGRectMake(plateRect.size.width / 2.0 + plateRadius / 1.4 * sinf(plateStartAngle) - plateRadius / 1.4 * sinf(M_PI / count), plateRect.size.height / 2.0 - plateRadius / 1.4 * cosf(plateStartAngle) - 25, plateRadius / 1.4 * sinf(M_PI / count) * 2, 50);
        plateTextLayer.string = self.data[i];
        plateTextLayer.affineTransform = CGAffineTransformMakeRotation(plateStartAngle);
        [self.plateShapeLayer addSublayer:plateTextLayer];
        
        CGFloat bigCircleLayerRadiu   = 5;
        CGFloat smallCircleLayerRadiu = 2.5;

        NSInteger number = -1;
        CALayer *bigCircleLayer = [CALayer layer];
        bigCircleLayer.cornerRadius = bigCircleLayerRadiu;
        bigCircleLayer.backgroundColor = [UIColor colorWithHexString:@"#ffffff"].CGColor;
        bigCircleLayer.frame = CGRectMake(width + circleRadius * sinf(plateStartAngle) + number * bigCircleLayerRadiu, height - circleRadius * cosf(plateStartAngle) + number * bigCircleLayerRadiu, bigCircleLayerRadiu * 2, bigCircleLayerRadiu * 2);
        [self.layer addSublayer:bigCircleLayer];
        
        CALayer *smallCircleLayer = [CALayer layer];
        smallCircleLayer.cornerRadius = smallCircleLayerRadiu;
        smallCircleLayer.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"].CGColor;
        smallCircleLayer.frame = CGRectMake(width + circleRadius * sinf(plateStartAngle + (M_PI * 2 / count) / 2.0) + number * smallCircleLayerRadiu, height - circleRadius * cosf(plateStartAngle + + (M_PI * 2 / count) / 2.0) + number * smallCircleLayerRadiu, smallCircleLayerRadiu * 2, smallCircleLayerRadiu * 2);
        [self.layer addSublayer:smallCircleLayer];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches
           withEvent:(UIEvent *)event {

    if (self.isplateAnimating) return;
    
    UITouch *anyTouch = [touches anyObject];
    CGPoint point = [anyTouch locationInView:self];
    if ([self layer:self.platePointLayer isContainsPoint:point]) {
        self.imageLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"start_point_img"].CGImage);
        if (self.delegate && [self.delegate respondsToSelector:@selector(plateViewDidBegin:)]) {
            [self.delegate plateViewDidBegin:self];
        } else {
            NSInteger targetIndex = arc4random() % self.data.count;
            [self startPlateAnimationWithTargetIndex:targetIndex];
        }
    }
}

- (void)startPlateAnimationWithTargetIndex:(NSInteger)targetIndex {
    if(![SmallDecisionsSingletonHelper shareInstance].isVIP) {
        NSUInteger number = [SmallDecisionsSingletonHelper getUserNumberWithKey:@"PLATEUSERNUMBER"];
        if(number > 9) {
            [SmallDecisionsSingletonHelper openVipViewController];
            return;
        } else {
            [SmallDecisionsSingletonHelper setUserNumberWithKey:@"PLATEUSERNUMBER" number:number + 1];
        }
    }
    // 圈数
    NSInteger count = self.data.count;
    count = MAX(6, self.data.count);
    count = MIN(count, 10);
    
    afterTime = 0.01;
    // 开始震动
    AudioServicesAddSystemSoundCompletion(1520, NULL, NULL, vibrationServiceSoundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(1520);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * (count - 2) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        afterTime = 0.02;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            afterTime = 0.04;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                afterTime = 0.08;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    afterTime = 0.16;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        afterTime = 0.3;
                    });
                });
            });
        });
    });

    self.targetIndex = targetIndex;
    self.isplateAnimating = YES;
    
    CABasicAnimation *plateBasicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    plateBasicAnimation.toValue = @((M_PI * 2 / self.data.count) * (self.data.count - targetIndex) + count * 2 * M_PI);
    plateBasicAnimation.duration = 0.75 * count + 0.75 * (self.data.count - targetIndex) / (CGFloat)self.data.count;
    plateBasicAnimation.repeatCount = 1.0;
    // 积累
    plateBasicAnimation.cumulative = YES;
    plateBasicAnimation.fillMode = kCAFillModeForwards;
    plateBasicAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    plateBasicAnimation.removedOnCompletion = NO;
    plateBasicAnimation.autoreverses   = NO;
    plateBasicAnimation.delegate       = self;
    [self.plateShapeLayer addAnimation:plateBasicAnimation forKey:@"RotationKey"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    self.imageLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"start_point_img"].CGImage);
    self.isplateAnimating = NO;
    if (self.delegate && [self.delegate respondsToSelector:@selector(plateViewDidFinish:target:)]) {
        [self.delegate plateViewDidFinish:self target:self.targetIndex];
    }
    // 结束震动
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(vibrationAudioServicePlaySystemSound) object:nil];
    AudioServicesDisposeSystemSoundID(1520);
    AudioServicesRemoveSystemSoundCompletion(1520);
    
}

- (BOOL)layer:(CALayer *)layer isContainsPoint:(CGPoint)point {
    CGRect plateRect = layer.frame;
    if (point.x >= plateRect.origin.x && point.x <= (plateRect.origin.x + plateRect.size.width) && point.y >= plateRect.origin.y && point.y <= plateRect.origin.y + plateRect.size.height) {
        
        return YES;
    }
    return NO;
}

- (void)vibrationAudioServicePlaySystemSound {
    AudioServicesPlaySystemSound(1520);
}

void vibrationServiceSoundCompleteCallback(SystemSoundID sound,void * clientData) {
    if (sound == 1520) {
        [plateView performSelector:@selector(vibrationAudioServicePlaySystemSound) withObject:nil afterDelay:afterTime];
    } else {
        // 注销声音播放完成事件回调函数
        AudioServicesRemoveSystemSoundCompletion(sound);
        // 释放SystemSoundID
        AudioServicesDisposeSystemSoundID(sound);
    }
}

- (CALayer *)platePointLayer {
    if (!_platePointLayer) {
        _platePointLayer = [CALayer layer];
        _platePointLayer.backgroundColor = [UIColor clearColor].CGColor;
    }
    return _platePointLayer;
}

- (CAShapeLayer *)plateShapeLayer {
    if (!_plateShapeLayer) {
        _plateShapeLayer = [CAShapeLayer layer];
        _plateShapeLayer.fillColor = [UIColor colorWithRed:0.99 green:0.89 blue:0.66 alpha:1].CGColor;
    }
    return _plateShapeLayer;
}

- (CALayer *)imageLayer {
    if (!_imageLayer) {
        _imageLayer = [CALayer layer];
        _imageLayer.cornerRadius = 35;
        _imageLayer.backgroundColor = [UIColor clearColor].CGColor;
        _imageLayer.contentsScale = [UIScreen mainScreen].scale;
        _imageLayer.contentsGravity = kCAGravityCenter;
        _imageLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"start_point_img"].CGImage);
        [self.platePointLayer addSublayer:_imageLayer];
    }
    return _imageLayer;
}


- (void)resetPlate {
    plateView = nil;
    afterTime = 0;
}

@end
